#!/bin/bash  
# 匹配提示符  
CMD_PROMPT="\](\$|#)"  
  
# 要执行的脚本  
file="cmd.sh"
# 数据文件  
data="data.txt" 
# ssh用户名 
username="username"  
# ssh密码
password="your password"
# ssh端口
port=22  
# 远程操作路径
address="/root/"

while read line
do
   host=$line
   echo HOST $host 
   expect -c "  
     spawn scp $file $username@$host:$address
     expect {  
         *yes/no* { send -- yes\r;exp_continue;}  
         *assword* { send -- $password\r;}  
     }
     expect eof
     spawn scp $data $username@$host:$address
     expect {  
         *yes/no* { send -- yes\r;exp_continue;}  
         *assword* { send -- $password\r;}  
     }
     expect eof
     send_user connecting\ to\ $host...\r
     spawn ssh -p $port $username@$host
     expect {  
         *yes/no* { send -- yes\r;exp_continue;}  
         *assword* { send -- $password\r;}  
     }
     expect -re $CMD_PROMPT  
     #给shell脚本添加权限
     send \"chmod a+x $address$file\r\"
     expect -re $CMD_PROMPT  
     #执行shell脚本
     send \"sh $address$file\r\"
     expect -re $CMD_PROMPT  
     #删除远程服务器上的shell脚本
     #send \"rm $address$file\r\"
     #expect -re $CMD_PROMPT  
     #退出
     send \"exit\r\"
     expect eof
   "  
   echo "\r"  
done < ./hostlist.txt
  
